package com.rjkj.medicalwaste.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.paging.AsyncPagingDataDiffer
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.rjkj.medicalwaste.R
import com.rjkj.medicalwaste.bean.*

class OpenBoxAdapter(private val itemClick: ItemClick<GarbageBean>) : PagingDataAdapter<GarbageBean, OpenBoxAdapter.ViewHolder>(COMPARATOR) {

    companion object {
        private val COMPARATOR = object : DiffUtil.ItemCallback<GarbageBean>() {
            override fun areItemsTheSame(oldItem: GarbageBean, newItem: GarbageBean): Boolean {
                return oldItem.garbageQRCode == newItem.garbageQRCode
            }

            override fun areContentsTheSame(oldItem: GarbageBean, newItem: GarbageBean): Boolean {
                return oldItem == newItem
            }
        }
    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val weight: TextView = itemView.findViewById(R.id.tv_weight)
        val tvDepartment: TextView = itemView.findViewById(R.id.tv_department)
        val tvTimeYmd: TextView = itemView.findViewById(R.id.tv_time_ymd)
        val tvTimeHms: TextView = itemView.findViewById(R.id.tv_time_hms)
        val tvType: TextView = itemView.findViewById(R.id.tv_type)
        val btDelete: ImageView = itemView.findViewById(R.id.bt_delete)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val garbageBean = getItem(position)
        if (garbageBean != null) {
            holder.weight.text = garbageBean.garbageWeight
            holder.tvDepartment.text = garbageBean.departmentName
            garbageBean.garbageTime.split(" ").let {
                if (it.size >= 2) {
                    holder.tvTimeYmd.text = it[0].substring(2, it[0].length)
                    holder.tvTimeHms.text = it[1]
                }
            }
            MedicalWasteType.getTypeByTypeName(garbageBean.garbageType).let {
                holder.tvType.text = it.alias
                if (it.bgId != 0)
                    holder.tvType.setBackgroundResource(it.bgId)
            }

            holder.btDelete.setOnClickListener {
                itemClick.onClicked(it, garbageBean)
            }


        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_open_box, parent, false)
        return ViewHolder(view)
    }
}